const Service = require("egg").Service;

const columns = ['book_cate_id', 'book_cate_name', 'book_cate_value', 'createtime', 'updatetime']

class CateService extends Service {
  // 检查分类是否存在
  async checkCate(params) {
    const res = await this.app.mysql.query(
      "select * from book_cate where book_cate_name=? or book_cate_value=?",
      [params.catename, params.catevalue]
    );
    return !!res[0];
  }

  // 新增分类
  async create(params) {
    const { ctx, app } = this;
    return app.mysql.insert("book_cate", {
      book_cate_id: ctx.uuid(),
      book_cate_name: params.catename,
      book_cate_value: params.catevalue,
      createtime: ctx.cTime(),
      updatetime: ctx.cTime(),
    });
  }
  // 删除分类
  async delete(params) {
    const { app } = this;
    return await app.mysql.delete('book_cate', {
        book_cate_id: params.id
    })
  }
  // 修改分类
  async update(params) {
    const { ctx, app } = this;
    return await app.mysql.update("book_cate", {
      book_cate_name: params.catename,
      book_cate_value: params.catevalue,
      updatetime: ctx.cTime()
    }, {
      where: {
        book_cate_id: params.cateid
      }
    });
  }
  // 查询分类（分页）
  async list(params) {
    const { ctx, app } = this;
    // 查询数据总数
    const total = await app.mysql.select("book_cate");

    let queryStr;

    const condition = ctx.condition(params)
    console.log(condition)

    if(condition.has){
      queryStr = `select ${columns.join(',')} from book_cate where ${condition.str} order by createtime desc limit ${
        params.pagesize
      } offset ${params.pagesize * params.pagenum - params.pagesize}`
    }else {
      queryStr = `select ${columns.join(',')} from book_cate order by createtime desc limit ${
        params.pagesize
      } offset ${params.pagesize * params.pagenum - params.pagesize}`
    }

    const data = await app.mysql.query(queryStr)
    return { data, total: total.length };
  }
  // 查询分类（列表）
  async listselect(){
    const { app } = this
    return await app.mysql.select('book_cate')
  }
}

module.exports = CateService;
